import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
/*
 *  A class that listens to the port number and accepts
 *  requests from a java client (Applet).
 */
public class networkHandler {
	private int port;
	private ServerSocket serverSocket;
	private Socket connection;
    private PrintWriter out;
    private BufferedReader in;
    private DataInputStream din;
    private DataOutputStream dout;
	
    /* The class is initiated given a port number.*/
	public networkHandler(int port) {
		this.port = port;
		this.serverSocket = null;
		this.connection = null;
        this.in = null;
        this.out = null;
	}
	/*
	 * Waits until a client has connected to the server
	 * and establishes a connection.
	 */
	public void connect() throws IOException {
		serverSocket = new ServerSocket(port);
        System.out.println("Waiting for connection");
        connection = serverSocket.accept();
        System.out.println("Connection received from " + connection.getInetAddress().getHostName());
        //get Input and Output streams
        out = new PrintWriter(connection.getOutputStream(), true);
        out.flush();
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        din = new DataInputStream(connection.getInputStream()); 
        dout = new DataOutputStream(connection.getOutputStream()); 
	}
	
	public DataInputStream getDin() {
		return this.din;
	}
	
	public DataOutputStream getDout() {
		return this.dout;
	}	
	/*
	 * Wait for the client to send us data.
     * NOTE: this class probably needs changing because
     * readline terminates a string when \n is encoountered.
	 */
	public String read() throws IOException {
        return in.readLine();
	}
	
	/*
	 * Send String formated message to client.
	 */
	public void send(String resp) {
        out.write(resp);
        out.flush(); 
	}
	
	/*
	 *  Close (safely) streams and sockets. 
	 */
	public void close() throws IOException {
        out.close();
        in.close();
        connection.close();
        serverSocket.close();
	}
	
	/* STUB */
	public boolean hasNext() {
		// TODO Auto-generated method stub
		
		System.out.println("hasNext stub in networkHandler -- always returns false.");
		return false;
	}
	public String recieve() {
		// TODO Auto-generated method stub
		System.out.println("recieve stub in networkHandler -- always returns empty string.");
		return "";
	}
	public boolean isConnected() {
		// TODO Auto-generated method stub
		System.out.println("isConnected stub in networkHandler -- always returns false.");
		return true;
	}
	
	//Send image. 
	public void sendImg(BufferedImage img)
	{
		
	}
}
